package main

import (
	"fmt"
	"regexp"
	"strconv"
	"strings"
)

/*
	已知火星人使用的运算符为#、$，其与地球人的等价公式如下：
	x#y = 4*x+3*y+2
	x$y = 2*x+y+3
	1、其中x、y是无符号整数
	2、地球人公式按C语言规则计算
	3、火星人公式中，#的优先级高于$，相同的运算符，按从左到右的顺序计算
	现有一段火星人的字符串报文，请你来翻译并计算结果。
*/

func main() {
	fmt.Println(getResult("7#6$5#12"))
}

/*
FindStringSubmatch returns a slice of strings holding the text of the leftmost match of the regular expression in s
and the matches, if any, of its subexpressions, as defined by the 'Submatch' description in the package comment.
A return value of nil indicates no match.

FindString returns a string holding the text of the leftmost match in s of the regular expression.
If there is no match, the return value is an empty string, but it will also be empty if the regular
expression successfully matches an empty string.
Use Regexp.FindStringIndex or Regexp.FindStringSubmatch if it is necessary to distinguish these cases.
*/

func getResult(str string) int64 {
	reg := regexp.MustCompile(`(\d+)\$(\d+)`)
	for reg.MatchString(str) {
		// subStr := reg.FindString(str)
		submatch := reg.FindStringSubmatch(str)
		fmt.Println(submatch)
		x, _ := strconv.ParseInt(submatch[1], 10, 64)
		y, _ := strconv.ParseInt(submatch[2], 10, 64)
		replacement := strconv.FormatInt(3*x+y+2, 10)
		str = reg.ReplaceAllString(str, replacement)
	}
	// 依据'#'分割字符串并计算最终结果
	parts := strings.Split(str, "#")
	var result int64
	for _, part := range parts {
		num, _ := strconv.ParseInt(part, 10, 64)
		if result == 0 {
			result = num
		} else {
			result = 2*result + 3*num + 4
		}
	}

	return result
}
